<?php

class OrderFeePay extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model("base_model");
        $this->load->model("order_model");
        $this->load->model("custom_model");
        $this->load->model("car_model");
        $this->load->model("custom_address_model");
        $this->load->model("province_model");
        $this->load->model("city_model");
        $this->load->model("district_model");
        $this->load->model("admin_user_model");
        $this->load->model("driver_model");
        $this->load->model("order_fee_model");
        $this->load->model("order_fee_pay_model");
        $this->load->model("order_genjin_model");
        $this->load->model("shouzhi_bank_model");

        $this->load->service("admin_manage_service");
        $this->check = $this->admin_manage_service;
        $this->_adminInfo = $this->check->checkAdminLogin();
        #

        $this->projectSet = [
            "url" => [
                "add" => MANAGE_URL . "&c=orderFeePay&m=add",
                "doAdd" => MANAGE_URL . "&c=orderFeePay&m=doAdd",
                "edit" => MANAGE_URL . "&c=orderFeePay&m=edit",
                "doEdit" => MANAGE_URL . "&c=orderFeePay&m=doEdit",
                "list" => MANAGE_URL . "&c=orderFeePay&m=lists",
                "batchDel" => MANAGE_URL . "&c=orderFeePay&m=batchDel",
                "doSelectIds" => MANAGE_URL . "&c=orderFeePay&m=doSelectIds",
                "view" => MANAGE_URL . "&c=orderFeePay&m=view",
                "getPreMileage" => MANAGE_URL . "&c=orderFeePay&m=getPreMileage",
                "getOrderWeight" => MANAGE_URL . "&c=orderFeePay&m=getOrderWeight",
                "batchPay" => MANAGE_URL . "&c=orderFeePay&m=batchPay",
                "doBatchPay" => MANAGE_URL . "&c=orderFeePay&m=doBatchPay",
            ],
            "file" => [
                "view" => "admin/orderFeePay",
                "js" => "admin/js/orderFeePay",
                "cache_ids_name" => "cache_orderFeePay_ids",
                "power_name" => "orderFeePay"
            ],
        ];
    }

    /*
     * 列表
     */

    function lists() {

        try {

            #权限
            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_view"));

            $page = $this->input->getInt("page", TRUE);
            if ($page <= 0) {
                $page = 1;
            }
            $pageCount = $this->input->getInt("limit", TRUE);
            if ($pageCount <= 0) {
                $pageCount = 50;
            }
            if ($pageCount >= 200) {
                $pageCount = 200;
            }
            $data["page"] = $page;
            $data["pageCount"] = $pageCount;

            $first = $this->input->getInt("first", true);
            if ($first == 1) {
                $this->session->unset_userdata([$this->projectSet["file"]["cache_ids_name"]]);
            }

            $searchParam = $this->_searchParam();
            $where = $searchParam["where"];
            $pageStrArr = $searchParam["pageStrArr"];
            foreach ($searchParam["data"] as $k => $v) {
                ${$k} = $v;
                $data[$k] = $v;
            }

            $data["navName"] = $type_id == 1 ? "收款记录" : "付款记录";

            $feeType = $this->order_fee_model->feeType();
            $data["feeType"] = $feeType;
            $unit = $this->order_fee_model->unit();
            $transportType = $this->order_fee_model->transportType();
            $data["transportType"] = $transportType;

            $data["shouzhiBank"] = $this->shouzhi_bank_model->getDataSetKey();
            $data["car"] = $this->car_model->getData("where status_id=1", 1, 0);
            $gongyingshang = $this->custom_model->getData("where type_id=1 and status_id=1", 1, 0, "");
            if (!empty($gongyingshang)) {
                $gongyingshang = array_column($gongyingshang, null, "id");
            }
            $data["gongyingshang"] = $gongyingshang;

            $sql = " from " . $this->order_fee_pay_model->tableName . " ofp";
            $sql .= " left join " . $this->order_model->tableName . " o on ofp.order_id=o.id";
            $sql .= " left join " . $this->car_model->tableName . " c on o.car_id=c.id";
            $sql .= " left join " . $this->shouzhi_bank_model->tableName . " sb on ofp.pay_shouzhi_bank_id=sb.id";
            if ($type_id == 2) {
                $sql .= " left join " . $this->order_fee_model->tableName . " of on of.id=ofp.order_fee_id";
                $sql .= " left join " . $this->custom_model->tableName . " cus on of.custom_id=cus.id";
            }

            $listNum = $this->base_model->getData("select count(o.id) as data_num,sum(ofp.total_fee) as sum_total_fee" . $sql . " " . $where, 1, 0, "");

            $is_ajax = $this->input->is_ajax_request();
            if ($is_ajax) {

                $select = "select ofp.*"
                        . ",o.order_no,o.order_date"
                        . ",c.car_number,sb.title";
                if ($type_id == 2) {
                    $select .= ",of.fee_type,of.unit,of.start_mileage,of.end_mileage,of.num,of.transport_type,of.unit_fee,of.custom_id";
                }

                //echo $select . $sql . " " . $where;

                $dataList = $this->base_model->getData($select . $sql . " " . $where, $page, $pageCount, "order by pay_time desc,id desc");

                foreach ($dataList as $k => $v) {
                    $dataList[$k]["order_date_tag"] = date("Y-m-d", $v["order_date"]);
                    $dataList[$k]["pay_time_tag"] = $v["pay_time"] ? date("Y-m-d", $v["pay_time"]) : "-";

                    if ($type_id == 2) {
                        $dataList[$k]["fee_type_name"] = $feeType[$v["fee_type"]]["name"];
                        $dataList[$k]["unit_name"] = $unit[$v["unit"]]["name"];
                        $xingshi_mileage = $v["end_mileage"] > 0 && $v["start_mileage"] > 0 ? $v["end_mileage"] - $v["start_mileage"] : 0;
                        $dataList[$k]["xingshi_mileage"] = $xingshi_mileage;
                        $dataList[$k]["youhao"] = $xingshi_mileage > 0 ? round((($v["num"] / $xingshi_mileage) * 100), 2) : "-";
                        $dataList[$k]["transport_type_tag"] = !empty($transportType[$v["transport_type"]]) ? $transportType[$v["transport_type"]]["name"] : "-";
                        $dataList[$k]["cmp_bf"] = !empty($gongyingshang[$v["custom_id"]]) ? $gongyingshang[$v["custom_id"]]["cmp_bf"] : "-";
                    }
                }
                $data["dataList"] = $dataList;

                $result = [
                    "code" => 0,
                    "count" => !empty($listNum) ? $listNum[0]["data_num"] : 0,
                    "data" => $dataList,
                    "msg" => "",
                    "totalRow" => [
                        "total_fee" => !empty($listNum) ? $listNum[0]["sum_total_fee"] : 0,
                    ],
                ];
                echo jsonEncode($result);
                exit;
            }

            #进行分页
            $pageStr = "";
            if (!empty($pageStrArr)) {
                foreach ($pageStrArr as $k => $v) {
                    $pageStr .= "&" . $k . "=" . $v;
                }
            }
            $data['base_url'] = $this->projectSet["url"]["list"] . $pageStr;

            $data["listNum"] = !empty($listNum) ? $listNum[0]["data_num"] : 0;
            $data["pageStr"] = $pageStr;

            $this->layout->view($this->projectSet["file"]["view"] . '/list', $data);
        } catch (Exception $e) {
            show_error($msg = $e->getMessage(), $e->getCode() ? $e->getCode() : 200, "系统提示");
        }
    }

    public function _searchParam() {

        $pageStrArr = array();
        $where = "where 1";

        //状态
        $type_id = $this->input->getPostInt("type_id", TRUE);
        if ($type_id > 0) {
            $pageStrArr["type_id"] = $type_id;
            $where .= " AND ofp.type_id = " . $type_id;
        }
        $data["type_id"] = $type_id;

        $fee_type = $this->input->getPostInt("fee_type", TRUE);
        if ($fee_type > 0) {
            $pageStrArr["fee_type"] = $fee_type;
            $where .= " AND of.fee_type = " . $fee_type;
        }
        $data["fee_type"] = $fee_type;

        $pay_shouzhi_bank_id = $this->input->getPostInt("pay_shouzhi_bank_id", TRUE);
        if ($pay_shouzhi_bank_id > 0) {
            $pageStrArr["pay_shouzhi_bank_id"] = $pay_shouzhi_bank_id;
            $where .= " AND ofp.pay_shouzhi_bank_id = " . $pay_shouzhi_bank_id;
        }
        $data["pay_shouzhi_bank_id"] = $pay_shouzhi_bank_id;

        $pay_time_range = $this->input->getPostStr("pay_time_range", TRUE);
        if ($pay_time_range != "") {
            $pay_time_range_arr = explode(" - ", $pay_time_range);
            $pay_time_start = strtotime($pay_time_range_arr[0]);
            $where .= " AND ofp.pay_time >=" . $pay_time_start;
            $pay_time_end = strtotime($pay_time_range_arr[1]) + 3600 * 24;
            $where .= " AND ofp.pay_time <" . $pay_time_end;
            $pageStrArr["pay_time_range"] = $pay_time_range;
        }
        $data["pay_time_range"] = $pay_time_range;

        $order_no = $this->input->getPostStr("order_no", TRUE);
        if ($order_no != "") {
            $pageStrArr["order_no"] = $order_no;
            $where .= " AND o.order_no like '%" . $order_no . "%'";
        }
        $data["order_no"] = $order_no;

        $transport_type = $this->input->getPostInt("transport_type", TRUE);
        if ($transport_type > 0) {
            $pageStrArr["transport_type"] = $transport_type;
            $where .= " AND of.transport_type = " . $transport_type;
        }
        $data["transport_type"] = $transport_type;

        $car_id = $this->input->getPostInt("car_id", TRUE);
        if ($car_id > 0) {
            $pageStrArr["car_id"] = $car_id;
            $where .= " AND o.car_id = " . $car_id;
        }
        $data["car_id"] = $car_id;

        $gongyingshang_custom_id = $this->input->getPostInt("gongyingshang_custom_id", TRUE);
        if ($gongyingshang_custom_id > 0) {
            $pageStrArr["gongyingshang_custom_id"] = $gongyingshang_custom_id;
            $where .= " AND of.custom_id = " . $gongyingshang_custom_id;
        }
        $data["gongyingshang_custom_id"] = $gongyingshang_custom_id;

        return [
            "data" => $data,
            "pageStrArr" => $pageStrArr,
            "where" => $where,
        ];
    }

    public function doSelectIds() {

        #权限
        //$this->check->checkPower(array("power" => "idcard_edit", "ajax" => 1));

        $flag = 0;
        $msg = "操作失败";
        $id_arr = $this->input->postStr("ids", TRUE, false);

        try {
            $sessionData = [
                $this->projectSet["file"]["cache_ids_name"] => $id_arr,
            ];
            $this->session->set_userdata($sessionData);

            $flag = 1;
            $msg = "操作成功";
            //事务结束
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }
        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * 
     */

    function batchPay() {

        try {
            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_pay"));

            $type_id = $this->input->getInt("type_id", true);
            if ($type_id <= 0) {
                throw new Exception("缺少收支类型");
            }
            $data["type_id"] = $type_id;

            $where = "";
            $is_sql = $this->input->getInt("is_sql", true);
            if ($is_sql == 1) {
                $searchParam = $this->_searchParam();
                $where = $searchParam["where"];
            } else {
                $cache_id_arr = $this->session->userdata($this->projectSet["file"]["cache_ids_name"]);
                if (empty($cache_id_arr)) {
                    throw new Exception("没有选择费用");
                }
                $ids = join(",", $cache_id_arr);
                $where = "where id in (" . $ids . ")";
            }
            $dataS = $this->order_fee_model->getData($where, 1, 0, "");
            if (empty($dataS)) {
                throw new Exception("不存在数据");
            }

            foreach ($dataS as $k => $v) {
                if ($v["pay_status"] == 1) {
                    throw new Exception("选中的费用已经有收付款");
                }
            }

            $data["shouzhiBank"] = $this->shouzhi_bank_model->getData("where status_id=1", 1, 0);

            $data["doAddUrl"] = $this->projectSet["url"]["doBatchPay"];

            $this->layout->view($this->projectSet["file"]["view"] . '/batchPay', $data);
        } catch (Exception $e) {
            show_error($msg = $e->getMessage(), $e->getCode() ? $e->getCode() : 200, "系统提示");
        }
    }

    function doBatchPay() {

        #权限

        $flag = 0;
        $msg = "操作失败";

        try {

            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_pay"));

            $needField = $this->order_fee_model->payNeedField();
            $fieldValue = $this->common->checkField($needField);

            $fieldValue["pay_time"] = strtotime($fieldValue["pay_time"]);

            $where = "";
            $is_sql = $this->input->getInt("is_sql", true);
            if ($is_sql == 1) {
                $searchParam = $this->_searchParam();
                $where = $searchParam["where"];
            } else {
                $cache_id_arr = $this->session->userdata($this->projectSet["file"]["cache_ids_name"]);
                if (empty($cache_id_arr)) {
                    throw new Exception("没有选择费用");
                }
                $ids = join(",", $cache_id_arr);
                $where = "where id in (" . $ids . ")";
            }
            $dataS = $this->order_fee_model->getData($where, 1, 0, "");
            if (empty($dataS)) {
                throw new Exception("不存在数据");
            }

            foreach ($dataS as $k => $v) {
                if ($v["pay_status"] == 1) {
                    throw new Exception("选中的费用已经有收付款");
                }
            }

            $id_arr = array_column($dataS, "id");
            $ids = join(",", $id_arr);

            $this->db->trans_start();

            $uData = array_merge($fieldValue, [
                "pay_status" => 1,
                "pay_updated_user_id" => $this->_adminInfo["id"],
                "updated_at" => time(),
            ]);
            $insert_id = $this->order_fee_model->updateData([
                "fieldArr" => $uData,
                "whereArr" => "id in(" . $ids . ")"
            ]);

            $flag = 1;
            $msg = "操作成功";

            $this->db->trans_complete();
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * 
     */

    public function batchDel() {

        #权限

        $flag = 0;
        $msg = "操作失败";

        try {

            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_del"));

            $where = "";
            $is_sql = $this->input->getInt("is_sql", true);
            if ($is_sql == 1) {
                $searchParam = $this->_searchParam();
                $where = $searchParam["where"];
            } else {
                $cache_id_arr = $this->session->userdata($this->projectSet["file"]["cache_ids_name"]);
                if (empty($cache_id_arr)) {
                    throw new Exception("没有选择数据");
                }
                $ids = join(",", $cache_id_arr);
                $where = "where id in (" . $ids . ")";
            }
            $dataS = $this->order_fee_pay_model->getData($where, 1, 0, "");
            if (empty($dataS)) {
                throw new Exception("不存在数据");
            }
            $order_id_arr = array_column($dataS, "order_id");
            $order_id_arr = array_unique($order_id_arr);
            if (count($order_id_arr) > 1) {
                throw new Exception("批量只能操作相同订单号的收付记录");
            }
            
            $type_id = $dataS[0]["type_id"];

            $order = $this->order_model->getDataById($order_id_arr[0]);
            if ($order["hexiao_status"] == 1) {
                throw new Exception("该订单已经核销，不可操作");
            }

            $id_arr = array_column($dataS, "id");
            $ids = join(",", $id_arr);

            $this->db->trans_start();

            if ($type_id == 2) {
                $order_fee_id_arr = array_column($dataS, "order_fee_id");
                $order_fee_ids = join(",", $order_fee_id_arr);
                $this->order_fee_model->updateData([
                    "fieldArr" => [
                        "pay_status" => 0,
                        "updated_at" => time(),
                    ],
                    "whereArr" => "id in(" . $order_fee_ids . ")",
                ]);
            }

            $this->order_fee_pay_model->delData([
                "whereArr" => "id in(" . $ids . ")",
            ]);

            $flag = 1;
            $msg = "操作成功";

            $this->db->trans_complete();
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

}
